﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.Drawing;
using System.Collections;
using System.IO;
using System.Threading;
using System.Runtime.InteropServices;
using DeviceSDK.LED;
using BaseHelper;
using BaseHelper.Base;

namespace DeviceSDK.LED.OnBon
{
    /// <summary>
    ///仰邦接收卡
    /// </summary>
    public class OnBon_BX5
    {
        [UnmanagedFunctionPointer(CallingConvention.Cdecl)]
        private delegate void SendProgramHandler();



        private static bool IsSending = false;
        private static bool IsInit = false;
        private static object locker = new object();


        public static string Get_Error(int ret)
        {
            switch (ret)
            {
                case 0:
                    return "操作成功！";

                case 1:
                    return "设备不支持！";
                    
                case 2:
                    return "创建节目失败！";

                case -1:
                    return "操作失败！";

                case -2:
                    return "发生错误！";

                case -3:
                    return "初始化失败！";

                default:
                    return "未知错误！";
            }
        }

        //public static int Get_Status(string IP)
        //{
        //    //2019.6.24 
        //    //LedYQNetSdk.Init();
        //    Init();
        //    short w = 0;
        //    short h = 0;
        //    ushort type = 0;
        //    int err=  LedYQNetSdk.Net_GetScreeninfo(IP, ref type, ref w, ref h);
        //    //LedYQNetSdk.Release();
        //    return err;
        //}


        public static int Init()
        {
            lock (locker)
            {
                try
                {
                    if (!IsInit)
                    {
                        int err=LedEQSdk.InitSdk();
                        LogHelper.Debug("Service.Release.Device.LED.OnBon.OnBon_BX5.cs", "InitSdk():" + err.ToString());
                    
                        if (err == 0)
                        {
                            Application.DoEvents();
                            IsInit = true;
                            return 0;

                        }
                        else
                            IsInit = false;

                    }
                }
                catch (Exception ex)
                {
                    LogHelper.Err("RT.Helper.Device.LED.OnBon.OnBon_BX5.cs", "Init()", ex);
                }
            }
            return IsInit?0:1;
        }
        public static void Delete(string IP)
        { 

            byte[] ip = Encoding.Default.GetBytes(IP);
            //获取节目列表
            byte[] arrPointer = new byte[Marshal.SizeOf(typeof(LedEQSdk.GetDirBlock_G56))];
            LedEQSdk.GetDirBlock_G56 driBlock;
            int err = LedEQSdk.cmd_ofsReedDirBlock(ip, 5005, arrPointer);
            IntPtr dec = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(LedEQSdk.GetDirBlock_G56)));
            Marshal.Copy(arrPointer, Marshal.SizeOf(typeof(LedEQSdk.GetDirBlock_G56)) * 0, dec, Marshal.SizeOf(typeof(LedEQSdk.GetDirBlock_G56)));
            driBlock = (LedEQSdk.GetDirBlock_G56)Marshal.PtrToStructure(dec, typeof(LedEQSdk.GetDirBlock_G56));
            Marshal.FreeHGlobal(dec);
            //获取节目详细信息
            IntPtr aa = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(LedEQSdk.GetDirBlock_G56)));
            Marshal.StructureToPtr(driBlock, aa, false);
            for (int i = 0; i < driBlock.fileNumber; i++)
            {
                byte[] fileAttrdata = new byte[Marshal.SizeOf(typeof(LedEQSdk.FileAttribute_G56))];
                LedEQSdk.FileAttribute_G56 fileAttr;
                err = LedEQSdk.cmd_getFileAttr(aa, (ushort)i, fileAttrdata);
                IntPtr dec1 = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(LedEQSdk.FileAttribute_G56)));
                Marshal.Copy(fileAttrdata, Marshal.SizeOf(typeof(LedEQSdk.FileAttribute_G56)) * 0, dec1, Marshal.SizeOf(typeof(LedEQSdk.FileAttribute_G56)));
                fileAttr = (LedEQSdk.FileAttribute_G56)Marshal.PtrToStructure(dec1, typeof(LedEQSdk.FileAttribute_G56));
                Marshal.FreeHGlobal(dec1);
                //删除指定节目
                err = LedEQSdk.cmd_ofsDeleteFormatFile(ip, 5005, 1, fileAttr.fileName);
            }
        }

        public static void Close()
        {
            LedEQSdk.ReleaseSdk();
        }
        //发送-节目
        public static int Send_Programs(string IP, int Width,int Height,PlaybillProgramInfo[] Programs)
        {
            int ret = 0;
            lock (locker)
            {
                try
                {

                    while (IsSending)
                        Thread.Sleep(1000);

                    LedEQSdk.InitSdk();
                    //if (Init() != 0)
                    //{
                    //    return -3;
                    //}
                    IsSending = true;
                   // Delete(IP);
                   
                    LedEQSdk.program_deleteProgram();
                    
                    ret=LedEQSdk.program_setScreenParams_G56(LedEQSdk.E_ScreenColor_G56.eSCREEN_COLOR_DOUBLE, 0x254, LedEQSdk.E_DoubleColorPixel_G56.eDOUBLE_COLOR_PIXTYPE_2);
                    if (ret != 0)
                    {
                        LogHelper.Debug("DeviceSDK.LED.OnBon.OnBon_BX5.cs", "program_setScreenParams_G56,ret:" + ret.ToString());
                    }
           
                    byte[] ip = Encoding.GetEncoding("GBK").GetBytes(IP);

                    LedEQSdk.EQprogramHeader header;
                    header.FileType = 0x00;
                    header.ProgramID = 0;
                    header.ProgramStyle = 0x00;
                    header.ProgramPriority = 0x00;
                    header.ProgramPlayTimes = 1;
                    header.ProgramTimeSpan = 0;
                    header.ProgramWeek = 0xff;
                    header.ProgramLifeSpan_sy = 0xffff;
                    header.ProgramLifeSpan_sm = 0x03;
                    header.ProgramLifeSpan_sd = 0x05;
                    header.ProgramLifeSpan_ey = 0xffff;
                    header.ProgramLifeSpan_em = 0x04;
                    header.ProgramLifeSpan_ed = 0x12;
                    header.PlayPeriodGrpNum = 0;
                    IntPtr aa = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(LedEQSdk.EQprogramHeader)));
                    Marshal.StructureToPtr(header, aa, false);
                    ret = LedEQSdk.program_addProgram(aa);

                    if (ret != 0)
                    {
                        aa = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(LedEQSdk.EQprogramHeader)));
                        Marshal.StructureToPtr(header, aa, false);
                        ret = LedEQSdk.program_addProgram(aa);
                        if (ret != 0)
                        {
                            if (ret != 0)
                            {
                                LogHelper.Debug("DeviceSDK.LED.OnBon.OnBon_BX5.cs", "program_addProgram,ret:" + ret.ToString());
                            }
                            LedEQSdk.ReleaseSdk();
                            IsSending = false;
                            return 2;//添加节目单失败
                        }
                    }


                    ushort areaID = 0;
                    LedEQSdk.EQareaHeader aheader = new LedEQSdk.EQareaHeader();
                    aheader.AreaType = 0;
                    aheader.AreaX = 0;
                    aheader.AreaY = 0;
                    aheader.AreaWidth = (ushort)Width;
                    aheader.AreaHeight = (ushort)Height;
                    IntPtr bb = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(LedEQSdk.EQareaHeader)));
                    Marshal.StructureToPtr(aheader, bb, false);
                    ret = LedEQSdk.program_AddArea(areaID, bb);  //添加图文区域

                    LedEQSdk.EQpageHeader pheader;
                    
                    foreach (PlaybillProgramInfo pinfo in Programs)
                    {
                        #region foreach


                        pheader = new LedEQSdk.EQpageHeader();

                        switch (pinfo.Type)
                        {
                            case "picture":
                            #region  图片
                            pheader.PageStyle = 0x00;
                            pheader.DisplayMode = 0x01;
                            pheader.ClearMode = 0x01;
                            pheader.Speed = 30;
                            pheader.StayTime = (ushort)(pinfo.PlayTime * 100);
                            pheader.RepeatTime = 1;
                            pheader.ValidLen = 0;
                            pheader.arrMode = LedEQSdk.E_arrMode.eSINGLELINE;
                            pheader.fontSize = 12;
                            pheader.color = (uint)LedEQSdk.E_Color_G56.eGREEN;
                            pheader.fontBold = false;
                            pheader.fontItalic = false;
                            pheader.tdirection = LedEQSdk.E_txtDirection.pNORMAL;
                            pheader.txtSpace = 0;
                            pheader.Valign = 2;
                            pheader.Halign = 2;

                            FileInfo f=new FileInfo(pinfo.FilePath);
                            if (!f.Exists)
                                continue;

                            if (f.Extension.ToLower() != ".png")
                            {
                                try
                                {
                                    string pngPath = f.FullName.Replace(f.Extension, ".png");
                                    Bitmap imgRead = (Bitmap)Image.FromFile(pinfo.FilePath);
                                    imgRead.Save(pngPath, System.Drawing.Imaging.ImageFormat.Png);
                                    imgRead.Dispose();
                                    pinfo.FilePath = pngPath;
                                }
                                catch { }
                    
                            }

                            //红色-绿色，颜色对调一下
                            //ChangeColorImage(pinfo.FilePath);

                            byte[] img = Encoding.Default.GetBytes(pinfo.FilePath);
                            IntPtr cc = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(LedEQSdk.EQpageHeader)));
                            Marshal.StructureToPtr(pheader, cc, false);
                            ret = LedEQSdk.program_pictureAreaAddPic(areaID, 0, cc, img);
                        

                            #endregion
                                break;

                            case "video":
                                continue;

                            case "rtf":
                                continue;

                            case "text":
                                #region 文字
                                
                                byte[] str = Encoding.Default.GetBytes(pinfo.Text.Replace("\r\n","\n"));
                                byte[] font = Encoding.Default.GetBytes(pinfo.FontName);
                                uint color;
                                if (pinfo.FontColor == "#00FF00")
                                    color = 0x02;
                                else if (pinfo.FontColor == "#FF0000")
                                    color = 0x01;
                                else if (pinfo.FontColor == "#FFFF00")
                                    color = 0x03;
                                else
                                    color = 0x01;

                                pheader.PageStyle = 0x00;
                                pheader.DisplayMode = pinfo.IsEffectRand==0?(byte)0x01:(byte)0x06;// 0x02;
                                pheader.ClearMode = 0x01;
                                pheader.Speed = 30;
                                pheader.StayTime = (ushort)(pinfo.PlayTime * 100);
                                pheader.RepeatTime = 1;
                                pheader.ValidLen = 0;
                                pheader.arrMode = LedEQSdk.E_arrMode.eMULTILINE;
                                pheader.fontSize = (ushort)pinfo.FontSize;
                                pheader.color = color; //0x01 绿色  0x02红色  0x03黄色
                                pheader.fontBold = pinfo.FontIsBold;
                                pheader.fontItalic = false;
                                pheader.tdirection = LedEQSdk.E_txtDirection.pNORMAL;
                                pheader.txtSpace = 0;
                                pheader.Valign = (byte)pinfo.PositionVer;// 2;
                                pheader.Halign = (byte)pinfo.PositionHor ;//2;
                                IntPtr dd = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(LedEQSdk.EQpageHeader)));
                                Marshal.StructureToPtr(pheader, dd, false);
                                ret = LedEQSdk.program_picturesAreaAddTxt(areaID, str, font, dd);

                                #endregion
                                break;
                        }


                        #endregion
                    }

                    ret = LedEQSdk.cmd_ofsStartFileTransf(ip, 5005);
                 
                    if (ret != 0)
                    {
                        if (ret != 0)
                        {
                            LogHelper.Debug("DeviceSDK.LED.OnBon.OnBon_BX5.cs", "cmd_ofsStartFileTransf,ret:" + ret.ToString());
                        }
                        LedEQSdk.ReleaseSdk();
                        IsSending = false;
                        return 2;
                    }
                    byte[] arrProgram = new byte[100];
                    LedEQSdk.EQprogram program;
                    ret = LedEQSdk.program_IntegrateProgramFile(arrProgram);
                   
                    if (ret != 0)
                    {
                        if (ret != 0)
                        {
                            LogHelper.Debug("DeviceSDK.LED.OnBon.OnBon_BX5.cs", "program_IntegrateProgramFile,ret:" + ret.ToString());
                        }
                        LedEQSdk.ReleaseSdk();
                        IsSending = false;
                        return 2;
                    }

                    IntPtr dec = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(LedEQSdk.EQprogram)));
                    Marshal.Copy(arrProgram, Marshal.SizeOf(typeof(LedEQSdk.EQprogram)) * 0, dec, Marshal.SizeOf(typeof(LedEQSdk.EQprogram)));
                    program = (LedEQSdk.EQprogram)Marshal.PtrToStructure(dec, typeof(LedEQSdk.EQprogram));
                    Marshal.FreeHGlobal(dec);

                    ret = LedEQSdk.cmd_ofsWriteFile(ip, 5005, program.fileName, program.fileType, program.fileLen, 1, program.fileAddre);

                    if (ret != 0)
                    {
                        LogHelper.Debug("DeviceSDK.LED.OnBon.OnBon_BX5.cs", "cmd_ofsWriteFile,ret:" + ret.ToString());
                        LedEQSdk.ReleaseSdk();
                        IsSending = false;
                        return 2;
                    }

                    ret = LedEQSdk.cmd_ofsEndFileTransf(ip, 5005);
                 
                    if (ret != 0)
                    {
                        LogHelper.Debug("DeviceSDK.LED.OnBon.OnBon_BX5.cs", "cmd_ofsEndFileTransf,ret:" + ret.ToString());
                        LedEQSdk.ReleaseSdk();
                        IsSending = false;
                        return 2;
                    }

                    ret = LedEQSdk.program_deleteProgram();

                    if (ret != 0)
                    {
                        LogHelper.Debug("DeviceSDK.LED.OnBon.OnBon_BX5.cs", "program_deleteProgram,ret:" + ret.ToString());
                    }
                    LedEQSdk.ReleaseSdk();
                    IsSending = false;
                    return 0;

                }
                catch (Exception ex)
                {
                    LogHelper.Err("DeviceSDK.LED.OnBon.OnBon_BX5.cs", "SendProgram()", ex);
                    IsSending = false;
                    return -2;
                }
                finally
                {
                    LedEQSdk.ReleaseSdk();
                    IsSending = false;
                }
            }//locker
          
        
        }



        public static bool ChangeColorImage(string FilePath)
        {
            FileInfo f = new FileInfo(FilePath);
            string tmpPath = f.FullName.Replace(f.Extension, "_tmp.png");
            Bitmap tmpImage = (Bitmap)Image.FromFile(FilePath);
            Bitmap pngImage = new Bitmap(tmpImage);
            tmpImage.Dispose();

            List<ImageHelper.ColorData> ltCD = new List<ImageHelper.ColorData>();
            ImageHelper.ColorData cd = new ImageHelper.ColorData();

            cd.ColorHex = "#00FF00";
            cd.NewColor = Color.White;
            ltCD.Add(cd);

            cd = new ImageHelper.ColorData();
            cd.ColorHex = "#FF0000";
            cd.NewColor = Color.FromArgb(0, 255, 0);
            ltCD.Add(cd);

            Bitmap newImage = ImageHelper.ColorChange(pngImage, null, ltCD);
            ltCD.Clear();

            cd = new ImageHelper.ColorData();
            cd.ColorHex = "#FFFFFF";
            cd.NewColor = Color.FromArgb(255, 0, 0);
            ltCD.Add(cd);

            newImage = ImageHelper.ColorChange(newImage, null, ltCD);
            newImage.Save(tmpPath, System.Drawing.Imaging.ImageFormat.Png);

            newImage.Dispose();
            try
            {
                File.Copy(tmpPath, FilePath, true);
                File.Delete(tmpPath);
            }
            catch 
            {
                return false;
            }
            return true; ;
        }
    }
}
